/* 
  用来登陆 获取用户各种信息 设置globaldata用
*/
const appGlobalData = getApp().globalData;
module.exports = class UserModule {
  constructor(showAuth, showPhone, startPageLogic) { // 用户角色
    this.showAuth = showAuth;
    this.startPageLogic = startPageLogic;
    this.showPhone = showPhone;
  }

  checkUserInfoAuth() { // 验证获取用户信息的权限
    wx.getSetting({ // 有授权就直接获取微信信息，无授权就询问权限，在第一步首先要拿到微信信息
      success: (res) => {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            withCredentials: true,
            lang: 'zh_CN',
            success: (res) => {
              appGlobalData.userWxInfo = res.userInfo;
              if (!appGlobalData.login) { // 需要登陆
                this.wxUsInfo = res;
                this.wxLogin();
              }
            },
            fail: (res) => {
              console.warn(res);
              this.showAuth()
            },
          })
        } else {
          this.showAuth();
        };
      },
      fail: function(res) {
        return false;
      },
      complete: function(res) {},
    })
  }
  getWxAuthCode(resolv, rejcet) { // 获取微信登陆code
    return new Promise(function(resolv, rejcet) {
      wx.login({
        success: function(res) {
          resolv(res);
        },
        fail: function(res) {
          rejcet(res);
        },
      })
    })
  }
  newLoginMethod(code, fullGetUserInfo, resl, rej) { // 新登陆方法
    return new Promise((resl, rej) => {
      const lauchOptions = getApp().globalData.launchOption;
      let _url = 'https://www.haitunxueche.com/user/studentLogin?code=' + code;
      if (lauchOptions.query && lauchOptions.query.sharefromuserid) {
        _url += '&shareOpenId=' + lauchOptions.query.sharefromuserid;
      }
      wx.request({
        url: _url,
        data: fullGetUserInfo,
        header: {},
        method: 'POST',
        success: function(res) {
          resl(res);
        },
        fail: function(res) {
          rej(res);
        },
        complete: function(res) {},
      })
    })
  }
  wxLogin() { // 微信的登陆功能  
    let fullGetUserInfo = this.wxUsInfo;
    this.getWxAuthCode()
      .then(d => { // 获取微信code
        if (d.code) {
          return d.code;
        } else {
          throw ('微信code获取失败');
        }
      })
      .then((code) => {
        // code 为微信登陆code
        return this.newLoginMethod(code, fullGetUserInfo)
      })
      .then(res => {
        if (res.data.code === 0) {
          // console.log('new login', res.data.data);
          if (res.data.data) {
            appGlobalData.login = {}; // 留下用户openid 和sessionkey 及可能的token
            for (let i in res.data.data) {
              if (i !== 'userInfo') {
                appGlobalData.login[i] = res.data.data[i];
              }
            }
          }
          appGlobalData.userInfo = res.data.data.userInfo;
          // 检查此用户学习
          if (res.data.data.userInfo && res.data.data.userInfo.subject > 0) {
            this.checkUserStudy();
          }
          if ((res.data.data.userInfo && !res.data.data.userInfo.mobile) || !res.data.data.userInfo) { // 没有手机号码，就跳转手机绑定
            this.showPhone();
          } else {
            this.startPageLogic();
          }
          // }


        } else {
          throw (res.data);
        }
      })
      .catch(e => {
        console.warn(e);
        wx.showModal({
          title: '错误',
          content: JSON.stringify(e),
          showCancel: false,
          confirmText: '关闭',
          confirmColor: '',
          success: function(res) {
            return null;
          },
        })
      })

  }
  reloadStudy(cb) { // 学生的学习信息使用getclass获取，不以学生状态为判断
    wx.request({
      url: 'https://www.haitunxueche.com/student/index/getClasses',
      data: '',
      header: {
        Authorization: appGlobalData.login.token,
      },
      method: 'GET',
      success: function(res) {
        if (res.data.code === 0) {
          appGlobalData.userStudyInfo = res.data.data;
          if (res.data.data.subject && (res.data.data.subject !== appGlobalData.userInfo.subject)) { // 修改用户信息里的subject
            appGlobalData.userInfo.subject = res.data.data.subject;
          }
          if (cb) {
            cb();
          }
        } else {
          wx.showModal({
            title: '错误',
            content: JSON.stringify(res.data),
            showCancel: false,
            confirmText: '关闭',
            confirmColor: '',
          })
        }
      },
      fail: function(res) {
        console.log(res);
      },
      complete: function(res) {},
    })
  }


  checkUserStudy() {
    const loadStudy = () => {
      wx.request({
        url: 'https://www.haitunxueche.com/student/index/getClasses',
        data: '',
        header: {
          Authorization: getApp().globalData.login.token,
        },
        method: 'GET',
        success: (res) => {
          // resolv(res);
          if (res.data.code === 0) {
            console.log(res);
            getApp().globalData.userStudyInfo = res.data.data;
          } else {
            getApp().globalData.userStudyInfo = null;
          }
        },
        fail: (res) => {
          getApp().globalData.userStudyInfo = null;
        },
      })
    }
    loadStudy();
  }
}
